package com.uam.core.lk.utils;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SignUtils {

    public static final String LK_SIGN_SALT = "D41D8CD98F00B204E9800998ECF8427E";

    public static void main(String[] args) {
        try {
            System.out.println(byte2hex(getMD5Digest("余额提现接口")));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //参数签名算法测试例子
        HashMap<String, String> signMap = new HashMap<String, String>();
        signMap.put("uid", "80575847438949f89fdcce8be6ea1bd6");
        signMap.put("money", "100");
        signMap.put("pay_channel", "2");
        signMap.put("channel_user_id", "111111111111111111111111111");
        signMap.put("userName", "小张");
        String sign = getSign(signMap, LK_SIGN_SALT);
        System.out.println("得到签名sign:" + sign);

        boolean bl = checkSign(signMap, sign);

        System.out.println("签名验证:" + bl);
    }

    /**
     * 签名验证
     * @param request
     * @return
     */
    public static Boolean checkSign(HashMap<String, String> params, String sign) {
        Boolean flag = false;

        if (sign.equals(getSign(params, LK_SIGN_SALT))) {
            flag = true;
        }
        return flag;
    }

    /**
     * 得到签名
     * @param params 参数集合不含secretkey
     * @param secret 验证接口的secretkey
     * @return
     */
    public static String getSign(Map<String, String> params, String secret) {
        String sign = "";
        StringBuilder sb = new StringBuilder();
        //step1：先对请求参数排序
        Set<String> keyset = params.keySet();
        TreeSet<String> sortSet = new TreeSet<String>();
        sortSet.addAll(keyset);
        Iterator<String> it = sortSet.iterator();
        //step2：把参数的key value链接起来 secretkey放在最后面，得到要加密的字符串
        while (it.hasNext()) {
            String key = it.next();
            String value = params.get(key);
            sb.append(key).append(value);
        }
        sb.append(secret);
        byte[] md5Digest;
        try {
            //得到Md5加密得到sign
            log.debug("排序后的：{}", sb.toString());
            md5Digest = getMD5Digest(sb.toString());
            sign = byte2hex(md5Digest);
        } catch (IOException e) {
            log.warn("生成签名失败：", e);
        }
        return sign;
    }

    private static byte[] getMD5Digest(String data) throws IOException {
        byte[] bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            bytes = md.digest(data.getBytes("UTF-8"));
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse);
        }
        return bytes;
    }

    private static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }
}
